package com.lyj.security.service;

import com.lyj.common.core.constants.CacheConstants;
import com.lyj.common.core.constants.JwtConstants;
import com.lyj.common.core.domain.LoginUser;
import com.lyj.common.core.utils.JwtUtils;
import com.lyj.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-08-12
 * Time: 22:39
 */
@Service
@Slf4j
public class TokenService {
    @Autowired
    private RedisService redisService;

    /**
     * 创建令牌
     */
    public String createToken(Long userId,String secret,Integer identity,String nickName,String headImage){
        //创建一个哈希表
        Map<String,Object> claims = new HashMap<>();
        //将需要填写在token中的数据插入
        claims.put(JwtConstants.LOGIN_USER_KEY,userId);
        //生成token
        String token = JwtUtils.createToken(claims,secret);

        //获得tokenKey，通过tokenKey作为redis建立联系的唯一标识
        String tokenKey = getTokenKey(String.valueOf(userId));
        //创建需要存储的敏感信息对象
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        //上传redis
        redisService.setCacheObject(tokenKey,loginUser,CacheConstants.EXPIRATION, TimeUnit.MINUTES);

        return token;
    }

    /**
     * 延长令牌的有效时间
     */
    public void extendToken (Claims claims){
        //首先拿到tokenKey
        String userKey  = getUserKey(claims);
        if(userKey == null){
            return;
        }
        String tokenKey = getTokenKey(String.valueOf(userKey));

        //通过tokenKey获得当前令牌有效剩余时间
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        //在有效时间在0-180min是进行延长
        if(expire != null&&expire<CacheConstants.REFRESH_TIME){
            //进行延长
            redisService.expire(tokenKey,CacheConstants.EXPIRATION,TimeUnit.MINUTES);
        }
    }

    /**
     *通过令牌获得敏感信息对象
     */
    public LoginUser getLoginUser(String token,String secret){
        String userKey = getUserKey(token,secret);
        if(userKey == null){
            return null;
        }
        String tokenKey =getTokenKey(userKey);
        return redisService.getCacheObject(tokenKey, LoginUser.class);
    }

    /**
     * 删除存储的敏感对象
     */
    public boolean deleteLoginUser(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null) {
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    /**
     *更新存储的敏感信息
     */
    public void refreshLoginUser(String nickName, String headImage, String userKey){
        String tokenKey =getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey,loginUser);
    }
    public String getUserKey(String token, String secret){
        //解析token
        Claims claims = getClaims(token,secret);
        if(claims == null){
            return null;
        }
        return JwtUtils.getUserKey(claims);
    }
    public Claims getClaims(String token, String secret){
        //解析token
        Claims claims;
        try{
            claims = JwtUtils.parseToken(token,secret);
            if(claims == null){
                log.error("解析token: {},出现异常",token);
                return null;
            }
        }catch (Exception e){
            log.error("解析token: {},出现异常",token);
            return null;
        }
        return claims;
    }
    public String getUserKey(Claims claims){
        if(claims == null){
            return  "";
        }
        return JwtUtils.getUserKey(claims);
    }
    private String getTokenKey(String userKey){
        return CacheConstants.LOGIN_TOKEN_KEY+userKey;
    }
}
